<template>
  <el-form
    ref="loginForm"
    :model="loginForm"
    :rules="loginRules"
    class="login-form"
    autocomplete="on"
    label-position="left"
    style="display: flex;flex-direction: column;justify-content: center;align-self: center;"
  >
    <el-form-item prop="phone">
      <span class="svg-container">
        <svg-icon icon-class="user" />
      </span>
      <el-input
        ref="phone"
        v-model="loginForm.phone"
        placeholder="请输入您的手机号"
        name="phone"
        type="text"
        tabindex="1"
        auto-complete="off"
      />
    </el-form-item>
    <el-form-item prop="password">
      <span class="svg-container">
        <svg-icon icon-class="password" />
      </span>
      <el-input
        :key="passwordType"
        ref="password"
        v-model="loginForm.password"
        :type="passwordType"
        placeholder="请输入您的密码"
        name="password"
        tabindex="2"
        auto-complete="on"
        @keyup.enter.native="handleLogin"
      />
      <span class="show-pwd" @click="showPwd">
        <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
      </span>
    </el-form-item>
    <el-form-item prop="captcha" class="captcha-formItem">
      <span class="svg-container">
        <svg-icon icon-class="verifyCode" />
      </span>
      <el-input
        v-model="loginForm.captcha"
        maxlength="4"
        placeholder="请输入验证码"
        @input="codeLogin"
        @keyup.enter.native="handleLogin"
      />
      <div style="cursor:pointer;" class="flex" @click="getCaptcha" v-html="svgCode" />
    </el-form-item>
    <el-form-item class="loginGN">
      <el-checkbox v-model="savePassBool" style="float: left;">记住密码</el-checkbox>
    </el-form-item>
    <el-button :loading="loading" type="primary" style="width:100%;" class="mt10" @click.native.prevent="handleLogin">登 录</el-button>
    <div style="position:relative;color: #606266;font-size: 14px;text-align: center;">
      没有账号？
      <el-button
        type="text"
        @click="toRegister"
      >点此注册</el-button>
    </div>
  </el-form>
</template>
<script>
import { isPhone } from '@/utils/validate'
import { getPass, setPass } from '@/utils/auth'
import { captcha } from '@/api/code'
export default {
  props: {
    activeName: {
      type: String,
      required: true
    }
  },
  data() {
    const validateUserphone = (rule, value, callback) => {
      if (!isPhone(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码不能少于6位'))
      } else {
        callback()
      }
    }
    return {
      loginRules: {
        phone: [{ required: true, trigger: 'blur', validator: validateUserphone }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        captcha: [
          { required: true, trigger: 'blur', message: '请输入验证码' },
          { min: 4, message: '长度4个字符', trigger: 'blur' }
        ]
      },
      passwordType: 'password', // 是否显示密码
      loading: false,
      loginForm: {
        phone: '',
        password: '',
        captcha: ''
      },
      svgCode: '', // 验证码图片svg
      savePassBool: false, // 记住密码
      redirect: undefined // 重定向地址
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    // 获取验证码
    this.getCaptcha()
    // 初始化信息
    if (localStorage.getItem('phone')) this.loginForm.phone = localStorage.getItem('phone') // 账号
    if (localStorage.getItem('savePassBool')) { // 是否记住密码
      this.savePassBool = JSON.parse(localStorage.getItem('savePassBool'))
      if (this.savePassBool) { // 记住密码true（获取密码）
        this.loginForm.password = getPass() || ''
      }
    }
  },
  mounted() {
    // 初始化就获得焦点
    if (this.loginForm.phone === '') {
      this.$refs.phone.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  methods: {
    // 点击注册
    toRegister() {
      this.$emit('update:activeName', 'register')
    },
    // 验证码输入框input回调（输入4位直接自动登录）
    codeLogin() {
      if (this.loginForm.captcha.length === 4) this.handleLogin()
    },
    // 获取验证码
    async getCaptcha() {
      const res = await captcha()
      if (res.code === 0) {
        const { data } = res
        this.svgCode = data
      }
    },
    // 点击登录
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', this.loginForm).then(() => {
            // 登陆成功
            this.$router.push({ path: this.redirect || '/' })
            this.setLoginForm() // 存储账号密码
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 存储账号密码
    setLoginForm() {
      localStorage.setItem('phone', this.loginForm.phone)
      localStorage.setItem('savePassBool', this.savePassBool)
      // 如果点击了保存密码
      if (this.savePassBool) {
        setPass(this.loginForm.password)
      }
    },
    // 点击图标
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    }
  }
}
</script>
<style lang="scss" >
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */
$bg: rgba($color: #ea64a2, $alpha: .2);
$light_gray: #606266;
$cursor: #606266;
@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-form .el-input input {
    color: $cursor;
  }
}
/* reset element-ui css */
.login-form{
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;
      font-size: 15px;
      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba($color: #ffffff, $alpha: .8);
    // ea64a2
    border-radius: 5px;
    color: #454545;
  }

  // 自己的
  .captcha-formItem{
    margin-bottom: 0;
    .el-form-item__content{
      display: flex;
      align-items: center;
    }
  }
  .loginGN{
    border: 0;
    background: transparent;
    margin-top: 10px;
    margin-bottom: 0px;
    .el-form-item__content{
      padding: 0 10px;
    }
    .el-checkbox__label{
      font-size: 15px;
    }
    .el-checkbox__inner{
      width: 16px;
      height: 16px;
    }
  }
}
// 验证码
// .captcha{
//   width: 100%;
//   height: 100%;
//   svg{
//     overflow: hidden;
//     width: 100%;
//     height: 100%;
//   }
// }
</style>

<style lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;
  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    // padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
</style>
